package com.learning.jquizenglish.common;

import android.app.Activity;
import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.learning.jquizenglish.R;
import com.learning.jquizenglish.screen.profile.ProfilePreference;

public class JQuizNoteManagement implements TabContentFactory, OnTabChangeListener{

	private TabHost 		mTabHost;
    private final String 	TAB_ONE_TAG = "Note";
    private final String 	TAB_TWO_TAG = "Web";
    private final int 		TAB_HEIGHT = 50; //set desired value here instead of 50
    private View tabOneContentView, tabTwoContentView;
	private View parentView;
	private Activity mContext;
	private EditText edtNote;
	private EditText edtBrowser;
	public void create(Activity context,View parent){
		mContext = context;
		parentView = parent;
		//setup Views for each tab
        setupViews();
        // call method to set up tabs
        setupTabs();
	}
	
	/**
     * Sets up the Views for each tab
     */
     public void setupViews() {
        tabOneContentView = parentView.findViewById(R.id.tabOneContentView);
        tabTwoContentView = parentView.findViewById(R.id.tabTwoContentView);
        //do whatever with the views here- for instance, set Adapters for ListViews or GridViews,
        //or set other values for other types of Views.
        initNoteTabContent();
        initWebTabContent();
     }
 
    /**
     * Sets up the tabs for this Activity
     */
    public void setupTabs() {
        mTabHost = (TabHost) parentView.findViewById(android.R.id.tabhost);
        mTabHost.setup();  //must be called
        mTabHost.setOnTabChangedListener(this);  //use this Activity as the onTabChangedListener
        //setup each individual tab
        setupTab(TAB_ONE_TAG);
        setupTab(TAB_TWO_TAG);
        setTabHeight(TAB_HEIGHT);
        // Workaround for "bleeding-through" overlay issue. Set each tab as current tab, by index.
        // Order should not matter, but the first tab to be shown should be set last.
        mTabHost.setCurrentTab(1);
        mTabHost.setCurrentTab(0);
    }
    
    /**
     * Sets up a new tab with given tag by creating a View for the tab (via
     * createTabView() ) and adding it to the tab host
     * @param tag The tag of the tab to setup
     */
    public void setupTab(String tag) {
        View tabView = createTabView(mTabHost.getContext(), tag);
//        mTabHost.addTab(mTabHost.newTabSpec(tag).setIndicator(tabView).setContent(this));
        mTabHost.addTab(mTabHost.newTabSpec(tag).setIndicator(tag).setContent(this));
    }
    
    /**
     * Creates a View for a tab
     * @param context The context from which the LayoutInflater is obtained
     * @param tag The tag to be used as the label on the tab
     * @return The inflated view to be used by a tab
     */
    private View createTabView(Context context, String tag) {
    	View view = LayoutInflater.from(mContext).inflate(R.layout.tab_indicator, null);
        TextView tv = (TextView) view.findViewById(R.id.tabLabel);
        //this sets the tab's tag as the label that displays on the view, but can be anything
        tv.setText(tag);
        return view;
    }
    
    private void initNoteTabContent(){
    	edtNote = (EditText) tabOneContentView.findViewById(R.id.edtNote);
    	String noteContent = ProfilePreference.getInstance().getNoteContent();
    	if (noteContent!=null && !noteContent.equals("")) {
			edtNote.setText(noteContent);
		}
    }
    
    public void saveJquizNote(){
    	String noteContent = edtNote.getText().toString();
    	if (noteContent!=null && !noteContent.equals("")) {
			ProfilePreference.getInstance().saveUserNote(noteContent);
		}
    }
    
    private void initWebTabContent(){
        edtBrowser = (EditText) tabTwoContentView.findViewById(R.id.edtInputUrl);
    	final WebView webView = (WebView) tabTwoContentView.findViewById(R.id.webView);
    	webView.setWebViewClient(new MyBrowser());
    	webView.getSettings().setBuiltInZoomControls(true);
    	webView.getSettings().setJavaScriptEnabled(true);
    	webView.getSettings().setUseWideViewPort(true);
    	webView.requestFocus(View.FOCUS_DOWN);
		webView.loadUrl("http://www.google.com");
		webView.setOnTouchListener(new View.OnTouchListener() { 
			@Override
			public boolean onTouch(View v, MotionEvent event) {
			           switch (event.getAction()) { 
			               case MotionEvent.ACTION_DOWN: 
			               case MotionEvent.ACTION_UP: 
			                   if (!v.hasFocus()) { 
			                       v.requestFocus(); 
			                   } 
			                   break; 
			           } 
			           return false; 
			        }
			});
    	EditText localEditext = edtBrowser;
    	localEditext.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_GO) {
					String value = edtBrowser.getText().toString();
    	        	if (value != null && value.length() >0) {
    	    			if (!value.startsWith("http://") && !value.startsWith("https://")) {
    	    				value = "http://" + value;
    	    			}
    	    		}
    	        	edtBrowser.setText(value);
    	        	webView.loadUrl(value);
    	        	InputMethodManager inputManager = (InputMethodManager)
    	                    mContext.getSystemService(Context.INPUT_METHOD_SERVICE); 

    	        	inputManager.hideSoftInputFromWindow(edtBrowser.getWindowToken(),0);
    	        	return true;
				}
				return false;
			}
		});
    	tabTwoContentView.findViewById(R.id.btnBack).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (webView.canGoBack()) {
					webView.goBack();
				}
			}
		});
    }
    
    /**
     * Sets a custom height for the TabWidget, in dp-units
     * @param height The height value, corresponding to dp-units
     */
    public void setTabHeight(int height) {
        for (int i = 0; i < mTabHost.getTabWidget().getTabCount(); i++) {
            mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height
                = (int) (height * mContext.getResources().getDisplayMetrics().density);
        }
    }

	@Override
	public void onTabChanged(String arg0) {
		InputMethodManager inputManager = (InputMethodManager)
                mContext.getSystemService(Context.INPUT_METHOD_SERVICE); 

    	inputManager.hideSoftInputFromWindow(edtNote.getWindowToken(),0);
	}

	@Override
	public View createTabContent(String tag) {
		if (tag.compareTo(TAB_ONE_TAG) == 0)
            return tabOneContentView;
        if (tag.compareTo(TAB_TWO_TAG) == 0)
            return tabTwoContentView;
        return null;
	}
	
	private class MyBrowser extends WebViewClient {
	      @Override
	      public boolean shouldOverrideUrlLoading(WebView view, String url) {
	         view.loadUrl(url);
	         return true;
	      }
	      
	      @Override
	    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
	    	  if ((event.getKeyCode() == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
	    		    view.goBack();
	    		    return true;
	    	  }

	    	  return super.shouldOverrideKeyEvent(view, event);
	    }
	}
}
